<?php
session_start();
require_once('../model/conn.php');
header('Content-Type: application/json');
$uName = $_SESSION['uName'];

// 处理头像上传
if (isset($_FILES['avatar'])) {
    $file = $_FILES['avatar'];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['code' => 500, 'msg' => '文件上传错误']);
        exit;
    }
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
    if (!in_array($file['type'], $allowedTypes)) {
        echo json_encode(['code' => 500, 'msg' => '只允许上传JPEG/PNG/GIF图片']);
        exit;
    }
    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $newFilename = uniqid() . '.' . $ext;
    $uploadPath = '../image/avatar/' . $newFilename;
    
    // 移动文件到目标目录
    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
        // 更新数据库
        $sql = "update tbl_user set avatar = '$newFilename' where uName = '$uName'";
        if (exec_update($sql) > 0) {
            echo json_encode([
                'code' => 200, 
                'msg' => '头像更新成功',
                'avatarUrl' => $newFilename
            ]);
        } else {
            echo json_encode(['code' => 500, 'msg' => '更新失败']);
        }
    } else {
        echo json_encode(['code' => 500, 'msg' => '文件保存失败']);
    }
    exit;
}

// 处理密码修改
$pwd = isset($_POST['pwd']) ? $_POST['pwd'] : null;
if ($pwd === null) {
  echo json_encode(['code' => 500, 'msg' => '请求失败']);
  exit;
}

$sql = "update tbl_user set uPass = '$pwd' where uName = '$uName';";
if (exec_update($sql) > 0) {
  echo json_encode(['code' => 200, 'msg' => '保存成功']);
} else {
  echo json_encode(['code' => 500, 'msg' => '保存失败']);
}
?>
